import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘远望
 * Date: 2025-04-21
 * Time: 21:17
 */
//优先级队列（堆）
public class MyHeap {
    public int[] elem;
    public int usedSize;

    public MyHeap(){
        this.elem = new int[10];
    }

    //初始化堆
    public void initElem(int[] array){
        for(int i = 0; i < array.length ; i++){
            this.elem[i] = array[i];
            this.usedSize++;
        }
    }

    //创建堆(大根堆)
    public void creatHrap(){
        for(int parent = (this.usedSize - 1 - 1) / 2 ; parent >= 0 ; parent--){
            siftDown(parent, this.usedSize);
        }
    }

    private void siftDown(int parent , int usedSize){
        int child = 2 * parent + 1;
        while(child < usedSize){
            //找到左右孩子的最大值
            if(child + 1 < usedSize && elem[child] < elem[child + 1]){
                child++;
            }
            if(elem[child] > elem[parent]) {
                swap(elem, child , parent);
                parent = child;
                child = 2 * parent + 1;
            }else {
                break;
            }
        }
    }
    private void swap(int[] elem , int i , int j){
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    //插入元素
    public void offer(int val){
        if(isFull()){
            elem = Arrays.copyOf(elem , elem.length * 2);
        }
        elem[usedSize] = val;
        siftUp(usedSize);
        usedSize++;
    }

    private void siftUp(int child){
        int parent = (child - 1) / 2;
        while (parent > 0){
            if(elem[parent] < elem[child]){
                swap(elem, child , parent);
                child = parent;
                parent = (child - 1) / 2;
            }else {
                break;
            }
        }
    }


    private boolean isFull(){
        return this.usedSize == elem.length;
    }

    //弹出元素
    public int poll() {
        if(isEmpty()){
            throw new EmptyException();
        }
        int val = elem[0];
        swap(elem , 0 , usedSize - 1);
        siftDown(0, usedSize - 1);
        usedSize--;
        return val;
    }

    //头元素
    public int peek(){
        if(isEmpty()){
            throw new EmptyException();
        }
        return elem[0];
    }

    private boolean isEmpty(){
        return usedSize == 0;
    }

    //从小到大排序
    public void heapSort(){
        int end = usedSize - 1;
        while(end > 0){
            swap(elem, 0 , end);
            siftDown(0 , end);
            end--;
        }
    }
}
